#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>

#define START 3000000
#define END   3001000
#define THREADS 4

static volatile int current;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

static void* check_prime(void* p) {
    while(1) {
        pthread_mutex_lock(&mtx);

        if(current == END + 1) {
            pthread_mutex_unlock(&mtx);
            pthread_exit(NULL);
        }

        int tmp = current++;
        pthread_mutex_unlock(&mtx);

        int is_prime = 1;
        for(int j = 2; j < tmp / 2; j++) {
            if(tmp % j == 0) {
                is_prime = 0;
                break;
            }
        }    

        if(is_prime)
            printf("%d is a prime number\n", tmp);
    }
}

int main() {
    current = START;
    int i, err;
    pthread_t threads[THREADS];

    for(i = 0; i < THREADS; i++) {
        err = pthread_create(threads + i, NULL, check_prime, NULL);
        if(err) {
            fprintf(stderr, "pthread_create: %s\n", strerror(err));
            exit(1);
        }
    }

    for(i = 0; i < THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&mtx);
}